<?php
/*
 * Author: Quan Van Sinh
 * Email : sinhvnb@vietnambiz.com
 * Mobile: 0972405165
*/
//category function
function addPropertyCategory() {
    global $db,$CONFIG;
    if(isset($_POST['submitFrmPropertyAddCategory'])) {
        $data = array();
        if($_POST['cat_title']=='') {
            $CONFIG["error_message"] .= "<li>Bạn chưa nhập tiêu đề!</li>";
        }
        $data['cat_title'] = $_POST['cat_title'];
        $data['cat_parent'] = $_POST['cat_parent'];
        $data['cat_link'] = create_link($_POST['cat_title']);
        $data['cat_link'] = checkCatLinkExist($data['cat_link']);
        $data['cat_description'] = $_POST['cat_description'];
        $data['lang'] = $_SESSION['adlang'];
        $data['create_date'] = date('Y-m-d H:i:s');
        $data['cat_active'] = $_POST['cat_active'];
        $data['user_id'] = $_SESSION['adlogin']["id"];

        if($CONFIG["error_message"]=='') {
            unset ($_REQUEST);
            $bigestOrder = getBigestCatOrder();
            $data['cat_order'] = $bigestOrder+1;
            $db->exec_insert('cat_property', $data);
            $CONFIG["success_message"] = "<li>Thêm mới danh mục thành công!</li>";
            if($_POST['submitType']=='exit') {
                server_redirect(SITE_URL . get_string_url(array('action')));
            }
        }
    }
}
function checkCatLinkExist($catLink) {
    global $db;
    $rsCat = $db->query_first("SELECT cat_id,cat_link FROM cat_property WHERE cat_link='$catLink'");
    if(intval($rsCat['cat_id'])>0) {
        $catLink = $rsCat['cat_link'].'-'.rand(0,9);
        checkCatLinkExist($catLink);
    }
    return $catLink;
}
function getBigestCatOrder() {
    global $db;
    $rsCat = $db->query_first("SELECT cat_order FROM cat_property ORDER BY cat_order DESC");
    return $rsCat['cat_order'];
}
function editUpdateCategory() {
    global $db,$CONFIG;
    $cat_id = intval($_REQUEST['cat_id']);
    if($cat_id>0) {
        if(isset($_POST['submitFrmPropertyAddCategory'])) {//update category
            $data = array();
            if($_POST['cat_title']=='') {
                $CONFIG["error_message"] .= "<li>Bạn chưa nhập tiêu đề!</li>";
            }
            $data['cat_title'] = $_POST['cat_title'];
            $data['cat_parent'] = $_POST['cat_parent'];
            $data['cat_link'] = create_link($_POST['cat_title']);
            $data['cat_description'] = filter($_POST['cat_description']);
            $data['create_date'] = date('Y-m-d H:i:s');
            $data['cat_active'] = filter($_POST['cat_active']);
            $data['user_id'] = $_SESSION['adlogin']["id"];
            if($CONFIG["error_message"]=='') {
                $db->exec_update('cat_property', $data, " cat_id=$cat_id ");
                $CONFIG["success_message"] = "<li>Cập nhật danh mục thành công!</li>";
                if($_POST['submitType']=='exit') {
                    server_redirect(SITE_URL . get_string_url(array('action')));
                }
            }
        }
        return $db->query_first("SELECT * FROM cat_property WHERE cat_id=$cat_id");
    }
}

function deletePropertyCat() {
    global $db;
    $cat_id = intval($_REQUEST['cat_id']);
    if($cat_id>0) {
        $arrChildCatProperty = getCatPropertyIdToArray($cat_id,$trees=null);
        for($i=0;$i<count($arrChildCatProperty);$i++) {
            if(intval($arrChildCatProperty[$i])>0) {
                $db->exec_delete('cat_property',"cat_id=".$arrChildCatProperty[$i]);
            }
        }
        $db->exec_delete('cat_property',"cat_id=$cat_id");
    }
}

function getCatPropertyIdToArray($parent_id = 0,$trees=null) {
    global $db;
    if(!$trees) $trees = array();
    $rsCat = $db->query("SELECT cat_id FROM cat_property WHERE  cat_parent = ".intval($parent_id));
    if($rsCat) {
        while($rs = $db->fetch_array($rsCat)) {
            $trees[] = $rs['cat_id'];
            $trees = getCatPropertyIdToArray($rs['cat_id'],$trees);
        }
    }
    return $trees;
}

function listAllPropertyCategory($parent_id = 0,$space = ' ', $trees = NULL) {
    global $db;
    if(!$trees) $trees = array();
    $rsCat = $db->query("SELECT * FROM cat_property WHERE  cat_parent = ".intval($parent_id)." AND lang='".$_SESSION['adlang']."' ORDER BY cat_order");
    while($rs=$db->fetch_array($rsCat)) {
        if($rs['cat_parent']==0) {
            $trees[] = array("cat_id"=>$rs['cat_id'],"cat_parent"=>$rs['cat_parent'],"cat_title"=>$rs['cat_title'],"cat_active"=>$rs['cat_active'],"create_date"=>$rs['create_date']);
        }else {
            $trees[] = array("cat_id"=>$rs['cat_id'],"cat_parent"=>$rs['cat_parent'],"cat_title"=>$space.$rs['cat_title'],"cat_active"=>$rs['cat_active'],"create_date"=>$rs['create_date']);
        }
        $trees = listAllPropertyCategory($rs['cat_id'],$space.'----',$trees);
    }
    return $trees;
}

function listPropertyCategoryByParent($parent_id = 0,$space = ' ', $trees = NULL) {
    global $db;
    if(!$trees) $trees = array();
    $rsCat = $db->query("SELECT * FROM cat_property WHERE  cat_parent = ".intval($parent_id)." ORDER BY cat_order,cat_id");
    while($rs=$db->fetch_array($rsCat)) {
        if($rs['cat_parent']==0) {
            $trees[] = array("cat_id"=>$rs['cat_id'],"cat_title"=>$rs['cat_title'],"cat_active"=>$rs['cat_active'],"create_date"=>$rs['create_date']);
        }else {
            $trees[] = array("cat_id"=>$rs['cat_id'],"cat_title"=>$space.$rs['cat_title'],"cat_active"=>$rs['cat_active'],"create_date"=>$rs['create_date']);
        }
    }
    return $trees;
}

function getPropertyCategoryParent($cat_id) {
    global $db;
    if(intval($cat_id)>0) {
        return $db->query_first("SELECT cat_parent FROM cat_property WHERE  cat_id = ".intval($cat_id));
    }
}

function getPropertyCategoryTitle($cat_id) {
    global $db;
    if(intval($cat_id)>0) {
        $rs = $db->query_first("SELECT cat_title FROM cat_property WHERE  cat_id = ".intval($cat_id));
    }
    return $rs['cat_title'];
}

function multiActionCategoryProperty() {
    global $db;
    if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'multiAction') {
        $arrCatId = $_REQUEST['arr_cat_id'];
        switch($_REQUEST['formPropertyCategoryViewAction']) {
            case "delete": {
                    for($i=0;$i<count($arrCatId);$i++) {
                        if(intval($arrCatId[$i])>0) {
                            $db->exec_delete('cat_property','cat_id='.intval($arrCatId[$i]));
                        }
                    }
                    break;
            }case


            "setStatusYes": {
                    for($i=0;$i<count($arrCatId);$i++) {
                        if(intval($arrCatId[$i])>0) {
                            $db->exec_update('cat_property',array("cat_active"=>'yes'),'cat_id='.intval($arrCatId[$i]));
                        }
                    }
                    break;
            }case


            "setStatusNo": {
                    for($i=0;$i<count($arrCatId);$i++) {
                        if(intval($arrCatId[$i])>0) {
                            $db->exec_update('cat_property',array("cat_active"=>'no'),'cat_id='.intval($arrCatId[$i]));
                        }
                    }
                    break;
                }
        }
    }
}

//order category
function orderProperty() {
    global $db,$CONFIG,$option;
    if(isset($_POST['submitFrmPropertyOrder']) && $_POST['submitFrmPropertyOrder']=="Submit") {//update
        if($option=='category') {//update category
            $arrPropertyCatID = $_POST['property_order'];
            if(count($arrPropertyCatID)) {
                for($i=0;$i<count($arrPropertyCatID);$i++) {
                    if(intval($arrPropertyCatID[$i])>0) {
                        $db->exec_update('cat_property',array("cat_order"=>$i),'cat_id='.intval($arrPropertyCatID[$i]));
                    }
                }
                if($_POST['submitType']=='exit') {
                    server_redirect(SITE_URL.get_string_url(array('action')));
                }else {
                    return listAllPropertyCategory();
                }
            }else {
                return listAllPropertyCategory();
            }
        }else if($option=='geo') {//update geographic
            $arrPropertyGeoID = $_POST['property_order'];
            if(count($arrPropertyGeoID)) {
                for($i=0;$i<count($arrPropertyGeoID);$i++) {
                    if(intval($arrPropertyGeoID[$i])>0) {
                        $db->exec_update('geographic',array("geo_order"=>$i),'geo_id='.intval($arrPropertyGeoID[$i]));
                    }
                }
                if($_POST['submitType']=='exit') {
                    server_redirect(SITE_URL.get_string_url(array('action')));
                }else {
                    return listAllPropertyGeographic();
                }
            }else {
                return listAllPropertyGeographic();
            }
        }
    }else {//show
        if($option=='category') {//show category
            return listAllPropertyCategory();
        }else if($option=='geo') {//show geographic
            return listAllPropertyGeographic();
        }
    }

}

// Le Trong Phuc
function upOrderPropertyCategory() {
    global $db;
    $cat_id = $_REQUEST['cat_id'];

    $arr_cat_order = getOrder($cat_id);
    $cat_order = $arr_cat_order['cat_order'];
    $cat_parent = $arr_cat_order['cat_parent'];
    $arrCatUp = getUpOrder($cat_order,$cat_parent);
    $catUpId = $arrCatUp['cat_id'];
    $catUpOrder = $arrCatUp['cat_order'];
    $data = array();
    $data['cat_order'] = $cat_order;


    $dataUp = array();
    $dataUp['cat_order'] = $catUpOrder;
    if(intval($catUpId>0)) {

        $db->query("update cat_property set cat_order=$catUpOrder where cat_id=$cat_id");
        $db->query("update cat_property set cat_order=$cat_order where cat_id=$catUpId");
    }
}
function getOrder($cat_id) {
    global $db;
    $rsCat = $db->query_first("SELECT cat_order,cat_parent FROM cat_property WHERE  cat_id = ".intval($cat_id));
    return $rsCat;
}
function getUpOrder($cat_order,$cat_parent) {
    global $db;
    $rsCat = $db->query_first("SELECT cat_id,cat_order FROM cat_property WHERE  cat_order<$cat_order AND cat_parent=$cat_parent ORDER BY cat_order DESC");
    return array("cat_id"=>$rsCat['cat_id'],"cat_order"=>$rsCat['cat_order']);
}
function downOrderPropertyCategory() {
    global $db;
    $cat_id = $_REQUEST['cat_id'];

    $arr_cat_order = getOrder($cat_id);
    $cat_order = $arr_cat_order['cat_order'];
    $cat_parent = $arr_cat_order['cat_parent'];
    $arrCatDown = getDownOrder($cat_order,$cat_parent);
    $catDownId = $arrCatDown['cat_id'];
    $catDownOrder = $arrCatDown['cat_order'];
    $data = array();
    $data['cat_order'] = $cat_order;


    $dataUp = array();
    $dataUp['cat_order'] = $catDownOrder;
    if(intval($catDownId)>0) {
        $db->query("update cat_property set cat_order=$catDownOrder where cat_id=$cat_id");
        $db->query("update cat_property set cat_order=$cat_order where cat_id=$catDownId");
    }


}
function getDownOrder($cat_order,$cat_parent) {
    global $db;
    $rsCat = $db->query_first("SELECT cat_id,cat_order FROM cat_property WHERE  cat_order>$cat_order AND cat_parent=$cat_parent ORDER BY cat_order ASC");
    return array("cat_id"=>$rsCat['cat_id'],"cat_order"=>$rsCat['cat_order']);
}
// End Le Trong Phuc

function getCategoryType($type='sell') {
    global $db,$CONFIG;
    if(isset($_REQUEST['type'])) {
        $cat_parent = intval($_REQUEST['type']);
    }else {
        $cat_parent = 1;
    }

    $rsCatProperty = $db->query("SELECT cat_id,cat_title FROM cat_property WHERE cat_parent=$cat_parent ORDER BY cat_order");
    $option = '<option value="0">Select category...</option>';
    while($rs=$db->fetch_array($rsCatProperty)) {
        if(isset($_REQUEST['cat_id']) && $_REQUEST['cat_id']==$rs['cat_id']) {
            $option .= '<option selected="selected" value="'.$rs['cat_id'].'">'.$rs['cat_title'].'</option>';
        }else {
            $option .= '<option value="'.$rs['cat_id'].'">'.$rs['cat_title'].'</option>';
        }
    }
    echo $option;
}
//end category function


//geographic function
function addPropertyGeographic() {
    global $db,$CONFIG;
    if(isset($_POST['submitFrmPropertyAddGeographic'])) {
        $data = array();
        if($_POST['geo_title']=='') {
            $CONFIG["error_message"] .= "<li>Bạn chưa nhập tiêu đề!</li>";
        }
        $data['geo_title'] = $_POST['geo_title'];
        $data['geo_parent'] = $_POST['geo_parent'];
        $data['geo_link'] = create_link($_POST['geo_title']);
        $data['geo_description'] = $_POST['geo_description'];
        $data['create_date'] = date('Y-m-d H:i:s');
        $data['geo_active'] = $_POST['geo_active'];
        $data['user_id'] = $_SESSION['adlogin']["id"];

        if($CONFIG["error_message"]=='') {
            unset ($_REQUEST);
            $bigestOrder = getBigestGeoOrder();
            $data['geo_order'] = $bigestOrder+1;
            $db->exec_insert('geographic', $data);
            $CONFIG["success_message"] = "<li>Thêm mới vị trí thành công!</li>";
            if($_POST['submitType']=='exit') {
                server_redirect(SITE_URL . get_string_url(array('action')));
            }
        }
    }
}

function getBigestGeoOrder() {
    global $db;
    $rsCat = $db->query_first("SELECT geo_order FROM geographic ORDER BY geo_order DESC");
    return $rsCat['geo_order'];
}

function editUpdateGeographic() {
    global $db,$CONFIG;
    $geo_id = intval($_REQUEST['geo_id']);
    if($geo_id>0) {
        if(isset($_POST['submitFrmPropertyAddGeographic'])) {//update category
            $data = array();
            if($_POST['geo_title']=='') {
                $CONFIG["error_message"] .= "<li>Title can not be blank!</li>";
            }
            $data['geo_title'] = $_POST['geo_title'];
            $data['geo_parent'] = $_POST['geo_parent'];
            $data['geo_link'] = create_link($_POST['geo_title']);
            $data['geo_description'] = filter($_POST['geo_description']);
            $data['create_date'] = date('Y-m-d H:i:s');
            $data['geo_active'] = filter($_POST['geo_active']);
            $data['user_id'] = $_SESSION['adlogin']["id"];
            if($CONFIG["error_message"]=='') {
                $db->exec_update('geographic', $data, " geo_id=$geo_id ");
                $CONFIG["success_message"] = "<li>Sửa vị trí thành công!</li>";
                if($_POST['submitType']=='exit') {
                    server_redirect(SITE_URL . get_string_url(array('action')));
                }
            }
        }
        return $db->query_first("SELECT * FROM geographic WHERE geo_id=$geo_id");
    }
}

function deletePropertyGeographic() {
    global $db;
    $geo_id = intval($_REQUEST['geo_id']);
    if($geo_id>0) {
        $arrChildGeoProperty = getGeoPropertyIdToArray($geo_id,$trees=null);
        for($i=0;$i<count($arrChildGeoProperty);$i++) {
            if(intval($arrChildGeoProperty[$i])>0) {
                $db->exec_delete('geographic',"geo_id=".$arrChildGeoProperty[$i]);
            }
        }
        $db->exec_delete('geographic',"geo_id=$geo_id");
    }
}

function getGeoPropertyIdToArray($parent_id = 0,$trees=null) {
    global $db;
    if(!$trees) $trees = array();
    $rsGeo = $db->query("SELECT geo_id FROM geographic WHERE  geo_parent = ".intval($parent_id));
    if($rsGeo) {
        while($rs = $db->fetch_array($rsGeo)) {
            $trees[] = $rs['geo_id'];
            $trees = getGeoPropertyIdToArray($rs['geo_id'],$trees);
        }
    }
    return $trees;
}

function listAllPropertyGeographic($parent_id = 0,$space = ' ', $trees = NULL) {
    global $db;
    if(!$trees) $trees = array();
    $rsCat = $db->query("SELECT * FROM geographic WHERE  geo_parent = ".intval($parent_id)." ORDER BY geo_order");
    while($rs=$db->fetch_array($rsCat)) {
        if($rs['geo_parent']==0) {
            $trees[] = array("geo_id"=>$rs['geo_id'],"geo_parent"=>$rs['geo_parent'],"geo_title"=>$rs['geo_title'],"geo_active"=>$rs['geo_active'],"create_date"=>$rs['create_date']);
        }else {
            $trees[] = array("geo_id"=>$rs['geo_id'],"geo_parent"=>$rs['geo_parent'],"geo_title"=>$space.$rs['geo_title'],"geo_active"=>$rs['geo_active'],"create_date"=>$rs['create_date']);
        }
        $trees = listAllPropertyGeographic($rs['geo_id'],$space.'----',$trees);
    }
    return $trees;
}

function getPropertyGeographicParent($geo_id) {
    global $db;
    if(intval($geo_id)>0) {
        return $db->query_first("SELECT geo_parent FROM geographic WHERE  geo_id = ".intval($geo_id));
    }
}

function getPropertyGeographicGrandParent($geo_id) {
    global $db;
    if(intval($geo_id)>0) {
        $rs1 = $db->query_first("SELECT geo_parent FROM geographic WHERE  geo_id = ".intval($geo_id));
        return $db->query_first("SELECT geo_parent FROM geographic WHERE  geo_id = ".intval($rs1['geo_parent']));
    }
}

function getPropertyGeographicTitle($geo_id) {
    global $db;
    if(intval($geo_id)>0) {
        $rs = $db->query_first("SELECT geo_title FROM geographic WHERE  geo_id = ".intval($geo_id));
    }
    return $rs['geo_title'];
}

function listAllPropertyGeographicByParent($parent_id = 0,$space = ' ', $trees = NULL) {
    global $db;
    if(!$trees) $trees = array();
    $rsCat = $db->query("SELECT * FROM geographic WHERE  geo_parent = ".intval($parent_id)." ORDER BY geo_order,geo_id");
    while($rs=$db->fetch_array($rsCat)) {
        if($rs['geo_parent']==0) {
            $trees[] = array("geo_id"=>$rs['geo_id'],"geo_title"=>$rs['geo_title'],"geo_active"=>$rs['geo_active'],"create_date"=>$rs['create_date']);
        }else {
            $trees[] = array("geo_id"=>$rs['geo_id'],"geo_title"=>$space.$rs['geo_title'],"geo_active"=>$rs['geo_active'],"create_date"=>$rs['create_date']);
        }
    }
    return $trees;
}

function getAjaxGeographic() {
    global $db;
    if(isset($_REQUEST['geo'])) {
        $geo_parent = intval($_REQUEST['geo']);
    }else {
        $geo_parent = 1;
    }
    $option = '<option value="0">Chọn vị trí...</option>';
    if(intval($geo_parent)>-1) {
        $rsGeoProperty = $db->query("SELECT geo_id,geo_title FROM geographic WHERE geo_parent=$geo_parent ORDER BY geo_order");
        while($rs=$db->fetch_array($rsGeoProperty)) {
            if(isset($_REQUEST['geo_id'])) {
                if($arrGeoID[0]==$rs['geo_id'] || $arrGeoID[1]==$rs['geo_id']) {
                    $option .= '<option selected="selected" value="'.$rs['geo_id'].'">'.$rs['geo_title'].'</option>';
                }else {
                    $option .= '<option value="'.$rs['geo_id'].'">'.$rs['geo_title'].'</option>';
                }
            }else {
                $option .= '<option value="'.$rs['geo_id'].'">'.$rs['geo_title'].'</option>';
            }
        }
    }
    echo $option;
}
function multiActionGeographicProperty() {
    global $db;
    if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'multiAction') {
        $arrCatId = $_REQUEST['arr_geo_id'];
        switch($_REQUEST['formPropertyGeographicViewAction']) {
            case "delete": {
                    for($i=0;$i<count($arrCatId);$i++) {
                        if(intval($arrCatId[$i])>0) {
                            $db->exec_delete('geographic','geo_id='.intval($arrCatId[$i]));
                        }
                    }
                    break;
            }case


            "setStatusYes": {
                    for($i=0;$i<count($arrCatId);$i++) {
                        if(intval($arrCatId[$i])>0) {
                            $db->exec_update('geographic',array("geo_active"=>'yes'),'geo_id='.intval($arrCatId[$i]));
                        }
                    }
                    break;
            }case


            "setStatusNo": {
                    for($i=0;$i<count($arrCatId);$i++) {
                        if(intval($arrCatId[$i])>0) {
                            $db->exec_update('geographic',array("geo_active"=>'no'),'geo_id='.intval($arrCatId[$i]));
                        }
                    }
                    break;
                }
        }
    }
}

// Le Trong Phuc
function upOrderPropertyGeographic() {
    global $db;
    $geo_id = $_REQUEST['geo_id'];

    $arr_geo_order = getOrderGeographic($geo_id);
    $geo_order = $arr_geo_order['geo_order'];
    $geo_parent = $arr_geo_order['geo_parent'];

    $arrGeoUp = getUpOrderGeographic($geo_order,$geo_parent);
    $geoUpId = $arrGeoUp['geo_id'];
    $geoUpOrder = $arrGeoUp['geo_order'];
    $data = array();
    $data['geo_order'] = $geo_order;


    $dataUp = array();
    $dataUp['geo_order'] = $geoUpOrder;
    if(intval($geoUpId>0)) {

        $db->query("update geographic set geo_order=$geoUpOrder where geo_id=$geo_id");
        $db->query("update geographic set geo_order=$geo_order where geo_id=$geoUpId");
    }
}
function getOrderGeographic($geo_id) {
    global $db;
    $rsGeo = $db->query_first("SELECT geo_order,geo_parent FROM geographic WHERE  geo_id = ".intval($geo_id));
    return $rsGeo;
}
function getUpOrderGeographic($geo_order,$geo_parent) {
    global $db;
    $rsGeo = $db->query_first("SELECT geo_id,geo_order FROM geographic WHERE  geo_order<$geo_order AND geo_parent=$geo_parent ORDER BY geo_order DESC");
    return array("geo_id"=>$rsGeo['geo_id'],"geo_order"=>$rsGeo['geo_order']);
}
function downOrderPropertyGeographic() {
    global $db;
    $geo_id = $_REQUEST['geo_id'];

    $arr_geo_order = getOrderGeographic($geo_id);
    $geo_order = $arr_geo_order['geo_order'];
    $geo_parent = $arr_geo_order['geo_parent'];

    $arrGeoDown = getDownOrderGeographic($geo_order,$geo_parent);
    $geoDownId = $arrGeoDown['geo_id'];
    $geoDownOrder = $arrGeoDown['geo_order'];
    $data = array();
    $data['geo_order'] = $geo_order;


    $dataUp = array();
    $dataUp['geo_order'] = $geoDownOrder;
    if(intval($geoDownId)>0) {
        $db->query("update geographic set geo_order=$geoDownOrder where geo_id=$geo_id");
        $db->query("update geographic set geo_order=$geo_order where geo_id=$geoDownId");
    }


}
function getDownOrderGeographic($geo_order,$geo_parent) {
    global $db;
    $rsGeo = $db->query_first("SELECT geo_id,geo_order FROM geographic WHERE  geo_order>$geo_order AND geo_parent=$geo_parent ORDER BY geo_order ASC");
    return array("geo_id"=>$rsGeo['geo_id'],"geo_order"=>$rsGeo['geo_order']);
}
// End Le Trong Phuc
//end geographic function

//start property function
function listAllProperty() {
    global $db,$CONFIG;
    if(isset($_REQUEST['page'])&& intval($_REQUEST['page'])>0) {
        $page = $_REQUEST['page'];
    }else {
        $page = 1;
    }
    // neu' bam vao nut tim kiem
    if(isset($_REQUEST['keyword'])&& $_REQUEST['keyword']!='') {
        $searchCondition = ' AND (n.title LIKE \'%'.$_REQUEST['keyword'].'%\' OR n.description LIKE \'%'.$_REQUEST['keyword'].'%\')';
    }
    if(isset($_REQUEST['cat_id'])&& intval($_REQUEST['cat_id'])>0) {
        $arrCatId = getCatPropertyIdToArray($_REQUEST['cat_id']);
        array_push($arrCatId,$_REQUEST['cat_id']);
        if(count($arrCatId)>0) {
            $strCatId = implode(',', $arrCatId);
            $searchCondition .= " AND c.cat_id IN ($strCatId)";
        }else {
            $searchCondition .= " AND c.cat_id =".$_REQUEST['cat_id'];
        }
    }
    //echo $searchCondition;
    $rsProperty = $db->query("SELECT n.id FROM property n LEFT JOIN cat_property c ON n.cat_id = c.cat_id WHERE 1 $searchCondition  AND n.lang='".$_SESSION['adlang']."' ORDER BY n.create_date DESC");
    $totalRows =  $db->num_rows($rsProperty);
    $totalPages = ceil($totalRows/$CONFIG ['rows_per_page_property']);
    $start = (($page*$CONFIG ['rows_per_page_property'])-$CONFIG ['rows_per_page_property']);
    $limit = $CONFIG ['rows_per_page_property'];

    $rs = $db->query("SELECT n.id,n.cat_id,n.title,n.title_link,n.description,n.create_date,n.type,n.status,c.cat_title
                            FROM property n LEFT JOIN cat_property c ON n.cat_id = c.cat_id
                            WHERE 1 $searchCondition AND n.lang='".$_SESSION['adlang']."' ORDER BY n.order_num  LIMIT $start,$limit");
    //chuyen ve` truong truoc neu' trang hien tai khong co' ban ghi nao (truong hop xoa)
    if($db->num_rows($rs)<1) {
        $page = $page - 1;
        if($page>1) {
            server_redirect(get_string_url()."&page=".$page);
        }

    }
    return array(
            "rs"=>$rs,
            "page"=>$page,
            "totalPages"=>$totalPages
    );

}

function addProperty() {
    global $db,$CONFIG;
    if(isset($_POST['submitFrmPropertyAdd'])) {
        $data = array();
        if($_POST['title']=='') {
            $CONFIG["error_message"] .= "<li>Bạn chưa nhập tiêu đề.</li>";
        }
        if($_POST['description']=='') {
            $CONFIG["error_message"] .= "<li>Bạn chưa nhập miêu tả.</li>";
        }
        $arrGeoId = $_POST['geo_id'];
        $geo_id = intval($arrGeoId[1]);
        if(intval($arrGeoId[1])==0) {
            $CONFIG["error_message"] .= "<li>Bạn chưa chọn quận huyện.</li>";
        }        
        $legal_doc = $_POST['legal_doc'];
        if(intval($legal_doc)==3) {
            if($_POST['other_legal_doc']!='') {
                $legal_doc = $_POST['other_legal_doc'];
            }else {
                $legal_doc = 'Giấy tờ khác';
            }
        }else {
            if(intval($legal_doc)==1) {
                $legal_doc = 'Sổ đỏ';
            }elseif(intval($legal_doc)==2) {
                $legal_doc = 'Sổ hồng';
            }else {
                $legal_doc = 'Giấy tờ khác';
            }
        }
        $arrImage = $_POST['thumb'];
        $create_date = date('Y-m-d H:i:s');
        if($_POST['type']==1) {
            $data['type'] = 'sell';
        }elseif($_POST['type']==2) {
            $data['type'] = 'rent';
        }else {
            $data['type'] = 'sell';
        }
        $data['cat_id'] = $_POST['cat_id'];
        $data['geo_id'] = $geo_id;
        $data['title'] = $_POST['title'];
        $data['title_link'] = create_link($_POST['title']);
        $data['title_link'] = checkPropertyLinkExist($data['title_link']);
        $data['thumb'] = $arrImage[0];
        $data['description'] = $_POST['description'];
        $data['direction'] = $_POST['direction'];
        $data['legal_doc'] = $legal_doc;
        $data['area_use'] = floatval($_POST['area_use']);
        $data['area_campus_width'] = floatval($_POST['area_campus_width']);
        $data['area_campus_depth'] = floatval($_POST['area_campus_depth']);
        $data['area_build'] = floatval($_POST['area_build']);
        $data['build_year'] = $_POST['build_year'];
        $data['repair_year'] = $_POST['repair_year'];
        $data['lang'] = $_SESSION['adlang'];
        $data['gara_oto'] = $_POST['gara_oto'];
        $data['org_price'] = $_POST['org_price'];
        if(isset($_POST['date_price']) && trim($_POST['date_price'])!='') {
            $data['date_price'] = $_POST['date_price'];
        }        
        if($data['area_build']==0) {
            $CONFIG["error_message"] .= "<li>Diện tích sàn phải lớn hơn 0!</li>";
        }
        $data['price'] = floatval(getPriceFloatMixString($_POST['price']));
        if($data['price']==0) {
            $CONFIG["error_message"] .= "<li>Giá phải là số và lớn hơn 0!</li>";
        }
        $data['room'] = intval($_POST['room']);
        $data['bathroom'] = intval($_POST['bathroom']);
        $data['bedroom'] = intval($_POST['bedroom']);
        $data['sittingroom'] = intval($_POST['sittingroom']);
        $data['kitchen'] = intval($_POST['kitchen']);
        $data['floor'] = intval($_POST['floor']);
        $data['way'] = floatval($_POST['way']);
        $data['status'] = $_POST['status'];
        $data['map'] = $_POST['map'];
        $data['create_date'] = $create_date;
        $data['member_id'] = 1;
        $data['last_edit'] = $create_date;
        $data['user_id'] = $_SESSION['adlogin']["id"];
        $data['user_last_edit'] = $create_date;        
        if(trim($_POST['num_order'])=='')
            $data['order_num'] =  1;
        else
            $data['order_num'] =$_POST['num_order'];

        $dataContact = array();
        $dataContact['name'] = $_POST['contactName'];
        $dataContact['email'] = $_POST['contactEmail'];
        $dataContact['address'] = $_POST['contactAddress'];
        $dataContact['phone'] = $_POST['contactPhone'];
        $dataContact['mobile'] = $_POST['contactMobile'];
        //Update order of other Property
       
        if($CONFIG["error_message"]=='') {
            $update_order="UPDATE property SET order_num=order_num+1 WHERE order_num>=".$data['order_num'];
            $db->query($update_order);
            unset ($_REQUEST);
            $db->exec_insert('property', $data);
            $propertyId = mysql_insert_id();
            $dataContact['property_id'] = $propertyId;
            $db->exec_insert('property_contact', $dataContact);
            //insert images
            for($i=0;$i<count($arrImage);$i++) {
                if($arrImage[$i]!='') {
                    $slideImage = $arrImage[$i];
                    $db->query("INSERT INTO property_image (property_id, image) VALUES ($propertyId, '$slideImage')");
                }
            }           
            if($_POST['submitType']=='exit') {
                server_redirect(SITE_URL . get_string_url(array('action')));
            }
            $CONFIG["success_message"] = "<li>Thêm mới bất động sản thành công!</li>";
        }

    }
}

function checkPropertyLinkExist($propertyLink) {
    global $db;
    $rs = $db->query_first("SELECT id,title_link FROM property WHERE title_link='$propertyLink'");
    if(intval($rs['id'])>0) {
        $propertyLink = $rs['title_link'].'-'.rand(0,9);
        checkPropertyLinkExist($propertyLink);
    }
    return $propertyLink;
}

function editUpdateProperty() {
    global $db,$CONFIG;
    $id = intval($_REQUEST['id']);
    if($id>0) {
        if(isset($_POST['submitFrmPropertyAdd'])) {
            $data = array();
            if($_POST['title']=='') {
                $CONFIG["error_message"] .= "<li>Bạn chưa nhập tiêu đề.</li>";
            }
            if($_POST['description']=='') {
                $CONFIG["error_message"] .= "<li>Bạn chưa nhập miêu tả.</li>";
            }
            $arrGeoId = $_POST['geo_id'];
            $geo_id = intval($arrGeoId[1]);
            if(intval($arrGeoId[1])==0) {
                $CONFIG["error_message"] .= "<li>Bạn chưa chọn quận huyện.</li>";
            }
            $legal_doc = $_POST['legal_doc'];
            if(intval($legal_doc)==3) {
                if($_POST['other_legal_doc']!='') {
                    $legal_doc = $_POST['other_legal_doc'];
                }else {
                    $legal_doc = 'Giấy tờ khác';
                }
            }else {
                if(intval($legal_doc)==1) {
                    $legal_doc = 'Sổ đỏ';
                }elseif(intval($legal_doc)==2) {
                    $legal_doc = 'Sổ hồng';
                }else {
                    $legal_doc = 'Giấy tờ khác';
                }
            }

            $arrImage = $_POST['thumb'];
            $edit_date = date('Y-m-d H:i:s');
            if($_POST['type']==1) {
                $data['type'] = 'sell';
            }elseif($_POST['type']==2) {
                $data['type'] = 'rent';
            }else {
                $data['type'] = 'sell';
            }
            $data['cat_id'] = $_POST['cat_id'];
            $data['geo_id'] = $geo_id;
            $data['title'] = $_POST['title'];
            $data['title_link'] = create_link($_POST['title']);
            $data['title_link'] = checkPropertyLinkExist($data['title_link']);
            $data['thumb'] = $arrImage[0];
            $data['description'] = $_POST['description'];
            $data['direction'] = $_POST['direction'];
            $data['legal_doc'] = $legal_doc;
            $data['area_use'] = floatval($_POST['area_use']);
            $data['area_campus_width'] = floatval($_POST['area_campus_width']);
            $data['area_campus_depth'] = floatval($_POST['area_campus_depth']);
            $data['area_build'] = floatval($_POST['area_build']);
            $data['build_year'] = $_POST['build_year'];
            $data['repair_year'] = $_POST['repair_year'];
            $data['gara_oto'] = $_POST['gara_oto'];
            $data['org_price'] = $_POST['org_price'];
             if(isset($_POST['date_price']) && trim($_POST['date_price'])!='') {
            $data['date_price'] = $_POST['date_price'];
            }

            if($data['area_build']==0) {
                $CONFIG["error_message"] .= "<li>Diện tích xây dựng phải là số và lớn hơn 0!</li>";
            }
            $data['price'] = floatval(getPriceFloatMixString($_POST['price']));
            if($data['price']==0) {
                $CONFIG["error_message"] .= "<li>Giá phải là số và lớn hơn 0!</li>";
            }
            $data['room'] = intval($_POST['room']);
            $data['bathroom'] = intval($_POST['bathroom']);
            $data['bedroom'] = intval($_POST['bedroom']);
            $data['sittingroom'] = intval($_POST['sittingroom']);
            $data['kitchen'] = intval($_POST['kitchen']);


            $data['floor'] = intval($_POST['floor']);
            $data['way'] = floatval($_POST['way']);
            $data['status'] = $_POST['status'];           
            $data['map'] = $_POST['map'];
            
            $data['user_id'] = $_SESSION['adlogin']["id"];
            $data['user_last_edit'] = $edit_date;
            if(trim($_POST['num_order'])=='')
                $data['order_num'] =  1;
            else
                $data['order_num'] =$_POST['num_order'];
            $dataContact = array();
            $dataContact['name'] = $_POST['contactName'];
            $dataContact['email'] = $_POST['contactEmail'];
            $dataContact['address'] = $_POST['contactAddress'];
            $dataContact['phone'] = $_POST['contactPhone'];
            $dataContact['mobile'] = $_POST['contactMobile'];

           
          
            if($CONFIG["error_message"]=='') {
                $update_order="UPDATE property SET order_num=order_num+1 WHERE order_num>".$data['order_num'];
                $db->query($update_order);
                unset ($_REQUEST);
                $db->exec_update('property', $data,"id=$id");
                if(checkContactPropertyExist($id)) {
                    $db->exec_update('property_contact', $dataContact,"property_id=$id");
                }else {
                    $db->exec_insert('property_contact', $dataContact);
                }
                //remove images being deleted
                $arrRemoveImage = $_POST['removeThumb'];
                for($i=0;$i<count($arrRemoveImage);$i++) {
                    if(intval($arrRemoveImage[$i])>0) {
                        $db->exec_delete('property_image', 'id='.$arrRemoveImage[$i]);
                    }
                }
                //insert images
                for($i=0;$i<count($arrImage);$i++) {
                    if($arrImage[$i]!='') {
                        $tempImageId = checkImageExist($id, $arrImage[$i]);
                        if($tempImageId=='donthave') {//chua ton` tai tag nay nen insert vao database
                            $slideImage = $arrImage[$i];
                            $db->query("INSERT INTO property_image (property_id, image) VALUES ($id, '$slideImage')");
                        }
                    }
                }
                
                if($_POST['submitType']=='exit') {
                    server_redirect(SITE_URL . get_string_url(array('action')));
                }
                $CONFIG["success_message"] = "<li>Cập nhật bất động sản thành công!</li>";
            }

        }
        $rsPropertyEdit = $db->query_first("SELECT * FROM property WHERE id=$id");
        $rsPropertyContactEdit = $db->query_first("SELECT * FROM property_contact WHERE property_id=".intval($id));
        return array("rsPropertyEdit"=>$rsPropertyEdit,"rsPropertyTagEdit"=>$rsPropertyTagEdit,"rsPropertyContactEdit"=>$rsPropertyContactEdit);
    }else {
        server_redirect(SITE_URL . get_string_url(array('action','id')));
    }

}

function deleteProperty() {
    global $db;
    $id = intval($_REQUEST['id']);
    if($id>0) {
        $db->exec_delete('property',"id=$id");
    }
}

function getPriceFloatMixString($haystack) {
    $arrNeedle = array('trieu','triệu','ty','tỷ');
    $haystack = strtolower($haystack);
    $value = 0;
    for($i=0;$i<count($arrNeedle);$i++) {
        $pos = strpos($haystack, $arrNeedle[$i]);
        if(($arrNeedle[$i]=='trieu' || $arrNeedle[$i]=='triệu') && intval($pos) > 0) {
            $value = floatval($haystack) * 1000000;
            $i=count($arrNeedle);
        }elseif(($arrNeedle[$i]=='ty' || $arrNeedle[$i]=='tỷ') && intval($pos) > 0) {
            $value = floatval($haystack) * 1000000000;
            $i=count($arrNeedle);
        }else if(intval($pos)==0) {
            $value = $haystack;
        }
    }
    return $value;
}

function checkImageExist($property_id,$image) {
    global $db;
    $rs = $db->query_first("SELECT id FROM property_image WHERE property_id=$property_id AND image='$image'");
    if($rs) {
        return $rs['id'];
    }else {
        return 'donthave';
    }
}

function checkContactPropertyExist($property_id) {
    global $db;
    $rs = $db->query_first("SELECT id FROM property_contact WHERE property_id=$property_id");
    if(intval($rs['id'])) {
        return true;
    }else {
        return false;
    }
}

function checkTagExist($tag) {
    global $db;
    $rs = $db->query_first("SELECT id FROM tags_property WHERE tags='$tag'");
    if($rs) {
        return $rs['id'];
    }else {
        return 'donthave';
    }
}

function multiActionProperty() {
    global $db;
    if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'multiAction') {
        $arrPropertyId = $_REQUEST['arr_property_id'];
        switch($_REQUEST['formPropertyViewAction']) {
            case "delete": {
                    for($i=0;$i<count($arrPropertyId);$i++) {
                        if(intval($arrPropertyId[$i])>0) {
                            $db->exec_delete('property','id='.intval($arrPropertyId[$i]));
                            $db->exec_delete('property_contact','id='.intval($arrPropertyId[$i]));
                            $db->exec_delete('property_image','id='.intval($arrPropertyId[$i]));
                        }
                    }
                    break;
            }case


            "actived": {
                    for($i=0;$i<count($arrPropertyId);$i++) {
                        if(intval($arrPropertyId[$i])>0) {
                            $db->exec_update('property',array("status"=>'actived'),'id='.intval($arrPropertyId[$i]));
                        }
                    }
                    break;
            }case


            "pending": {
                    for($i=0;$i<count($arrPropertyId);$i++) {
                        if(intval($arrPropertyId[$i])>0) {
                            $db->exec_update('property',array("status"=>'pending'),'id='.intval($arrPropertyId[$i]));
                        }
                    }
                    break;
            }case


            "closed": {
                    for($i=0;$i<count($arrPropertyId);$i++) {
                        if(intval($arrPropertyId[$i])>0) {
                            $db->exec_update('property',array("status"=>'closed'),'id='.intval($arrPropertyId[$i]));
                        }
                    }
                    break;
             }case


            "movetop": {
                 
                    for($i=0;$i<count($arrPropertyId);$i++) {
                        if(intval($arrPropertyId[$i])>0) {
                            $Max=$db->query_first("select max(order_num) as maxnum FROM property");
                            $orderNum=$Max["maxnum"]+1;                            
                            $db->exec_update('property',array("order_num"=>$orderNum),'id='.intval($arrPropertyId[$i]));
                        }
                    }
                    break;
                }

        }
    }
}


function propertyDetail() {
    global $db;
    $id = intval($_REQUEST['id']);
    if($id>0) {
        return $db->query_first("SELECT * FROM property WHERE id=$id");
    }else {
        server_redirect(ADMIN_URL.'?module=property');
    }
}

function showPropertyDirection($direction_number) {
    switch ($direction_number) {
        case 1:
            return 'Bắc';
            break;
        case 2:
            return 'Đông';
            break;
        case 3:
            return 'Đông bắc';
            break;
        case 4:
            return 'Đông nam';
            break;
        case 5:
            return 'Nam';
            break;
        case 6:
            return 'Tây';
            break;
        case 7:
            return 'Tây bắc';
            break;
        case 8:
            return 'Tây nam';
            break;
        default:
            break;
    }
}
//end property function

?>
